import React, { useState } from 'react';
import {
  LoginForm,
  ProFormText,
  ProFormCheckbox,
  ProCard
} from '@ant-design/pro-components';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { message, Button, Typography, Space } from 'antd';
import { history, Link } from 'umi';
import { login } from '@/services/user';
import { handleSuccessfulAuth } from '@/utils/auth';

const { Title, Paragraph } = Typography;

/**
 * 登录页面
 */
const LoginPage: React.FC = () => {
  const [loginError, setLoginError] = useState<string>('');
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<any>({});

  /**
   * 处理登录表单提交
   * @param values 表单值
   */
  const handleSubmit = async (values: any) => {
    try {
      setSubmitting(true);
      setLoginError('');

      const response = await login({
        englishName: values.username,
        password: values.password,
      });

      // 保存令牌和用户信息
      handleSuccessfulAuth(response.data.token, response.data.user);

      message.success('登录成功');

      // 跳转到仪表盘
//       history.push('/dashboard');
      history.push('/taskboard');
    } catch (error: any) {
      console.error('登录失败', error);
      setLoginError(error.message || '登录失败，请检查用户名和密码');
    } finally {
      setSubmitting(false);
    }
  };

  // 手动处理登录按钮点击
  const handleLoginClick = () => {
    const form = document.querySelector('form');
    if (form) {
      form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center login-bg py-12 px-4 sm:px-6 lg:px-8">
      <div className="w-full max-w-[460px]">
        <div className="text-center mb-10">
          <div className="flex items-center justify-center gap-2">
            <Title level={2} className="!text-[#1677ff] !m-0">存款AI共建平台</Title>
          </div>
        </div>

        {loginError && (
          <ProCard className="mb-6 border-l-4 border-l-red-500 bg-red-50" bordered={false}>
            <div className="text-red-600 flex items-center px-2">
              <div>
                <div className="font-medium">登录失败</div>
                <div className="text-sm mt-1">{loginError}</div>
              </div>
            </div>
          </ProCard>
        )}

        <ProCard
          headerBordered
          title={
            <div className="pt-2">
              <Title level={4} className="!m-0">账号登录</Title>
              <Paragraph type="secondary" className="text-xs mt-1">欢迎回来，请输入您的账号信息</Paragraph>
            </div>
          }
        >
          <LoginForm
            formRef={(formRef: any) => {
              if (formRef) {
                formRef.current?.setFieldsValue(formValues);
              }
            }}
            onValuesChange={(changedValues: any) => {
              setFormValues({ ...formValues, ...changedValues });
            }}
            submitter={false}
            onFinish={handleSubmit}
            style={{ overflow: 'visible' }}
          >
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined style={{ color: '#bfbfbf' }} />,
              }}
              placeholder="请输入用户名/英文名"
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
                {
                  min: 4,
                  message: '用户名长度至少为4个字符!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined style={{ color: '#bfbfbf' }} />,
              }}
              placeholder="请输入密码"
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
                {
                  min: 6,
                  message: '密码长度至少为6个字符!',
                },
              ]}
            />


            <Button
              type="primary"
              size="large"
              block
              onClick={handleLoginClick}
              loading={submitting}
              className="mt-6 h-11"
            >
              登录
            </Button>
          </LoginForm>

          <div className="text-center mt-6 border-t pt-5">
            <Space>
              <span className="text-gray-500">还没有账号?</span>
              <Link to="/auth/register" className="text-[#1677ff] hover:text-blue-600 font-medium">
                立即注册
              </Link>
            </Space>
          </div>
        </ProCard>

        <div className="text-center text-gray-400 text-xs mt-10">
          Copyright © {new Date().getFullYear()} 存款AI共建平台
        </div>
      </div>
    </div>
  );
};

export default LoginPage;